<template>
  <div>
    <!-- step one -->
    <a-form-model
      ref="ruleForm"
      :model="form"
      :rules="rules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
    >
      <a-card
        :bordered="false"
        style="margin-left: 16px;margin-right: 16px;margin-top: 16px;"
      >
        <p style="font-size:20px;font-weight:500">创建试卷</p>
        <a-card :bordered="false" style="background:rgb(246,250,255)">
          <div style="vertical-align:middle;">
            <div style="width:50px;float:left;heigth:50px">
              <span
                style="font-size:35px;font-weight:500;color:rgb(190,220,253)"
                >1</span
              >
            </div>
            <div style="width:150px;heigth:50px;float:left;line-height:50px">
              <span style="font-size:18px;font-weight:500">基本信息</span>
            </div>
          </div></a-card
        >
        <a-card :bordered="false">
          <a-form-model-item ref="name" label="试卷名称" prop="testName">
            <a-input style="width:300px" v-model="form.testName" />
          </a-form-model-item>
        </a-card>
        <!--step two -->
        <a-card :bordered="false" style="background:rgb(246,250,255)">
          <div style="vertical-align:middle;">
            <div style="width:50px;float:left;heigth:50px">
              <span
                style="font-size:35px;font-weight:500;color:rgb(190,220,253)"
                >2</span
              >
            </div>
            <div style="width:150px;heigth:50px;float:left;line-height:50px">
              <span style="font-size:18px;font-weight:500">试卷内容</span>
            </div>
          </div></a-card
        >
        <a-card :bordered="false">
          <a-row>
            <a-col :span="3">
              <div
                style="float:right;margin-right:5px;border:1px solid #e8e8e8;width:160px;margin-top:42px"
              >
                <!-- 统计 -->
                <div style="margin-top:10px">
                  <a-row>
                    <a-col style="margin-left:3px;color:#000;"
                      >试卷题目
                      <span style="color:#f81d22">
                        {{ information[2].total }}
                      </span>
                      题</a-col
                    >
                    <a-col style="margin-left:3px;color:#000;"
                      >试卷总分
                      <span style="color:#f81d22">
                        {{ information[2].totalScore }}
                      </span>
                      分</a-col
                    >
                  </a-row>
                </div>
                <!-- 填空题 -->
                <div style="margin-top:10px" v-if="information[0].Gap != 0">
                  <a-row>
                    <a-col style="margin-left:3px;color:#000;"
                      >填空题
                      <span style="color:#f81d22">
                        x {{ information[0].Gap }}</span
                      ></a-col
                    >
                    <a-col style="margin-top:3px;margin-left:3px" :span="6">
                      <span>每题</span>
                    </a-col>
                    <a-col style="margin-top:3px" :span="10">
                      <a-input-number
                        size="small"
                        :min="0"
                        :max="100"
                        :formatter="
                          value => `${value}分`.replace(/[^\d分]/g, '')
                        "
                        :parser="value => value.replace('分', '')"
                        v-model="information[1].Gap"
                        @change="changeScore(4)"
                      />
                    </a-col>
                  </a-row>
                </div>
                <!-- 判断题 -->
                <div style="margin-top:10px" v-if="information[0].TorF != 0">
                  <a-row>
                    <a-col style="margin-left:3px;color:#000;"
                      >判断题
                      <span style="color:#f81d22">
                        x {{ information[0].TorF }}</span
                      ></a-col
                    >
                    <a-col style="margin-top:3px;margin-left:3px" :span="6">
                      <span>每题</span>
                    </a-col>
                    <a-col style="margin-top:3px" :span="10">
                      <a-input-number
                        size="small"
                        :min="0"
                        :max="100"
                        :formatter="
                          value => `${value}分`.replace(/[^\d分]/g, '')
                        "
                        :parser="value => value.replace('分', '')"
                        v-model="information[1].TorF"
                        @change="changeScore(3)"
                      />
                    </a-col>
                  </a-row>
                </div>
                <!-- 单选题 -->
                <div style="margin-top:10px" v-if="information[0].Radio != 0">
                  <a-row>
                    <a-col style="margin-left:3px;color:#000;"
                      >单选题
                      <span style="color:#f81d22">
                        x {{ information[0].Radio }}</span
                      ></a-col
                    >
                    <a-col style="margin-top:3px;margin-left:3px" :span="6">
                      <span>每题</span>
                    </a-col>
                    <a-col style="margin-top:3px" :span="10">
                      <a-input-number
                        size="small"
                        :min="0"
                        :max="100"
                        :formatter="
                          value => `${value}分`.replace(/[^\d分]/g, '')
                        "
                        :parser="value => value.replace('分', '')"
                        v-model="information[1].Radio"
                        @change="changeScore(1)"
                      />
                    </a-col>
                  </a-row>
                </div>
                <!-- 多选题 -->
                <div
                  style="margin-top:10px"
                  v-if="information[0].MultiSelect != 0"
                >
                  <a-row>
                    <a-col style="margin-left:3px;color:#000;"
                      >多选题
                      <span style="color:#f81d22">
                        x {{ information[0].MultiSelect }}</span
                      ></a-col
                    >
                    <a-col style="margin-top:3px;margin-left:3px" :span="6">
                      <span>每题</span>
                    </a-col>
                    <a-col style="margin-top:3px" :span="10">
                      <a-input-number
                        size="small"
                        :min="0"
                        :max="100"
                        :formatter="
                          value => `${value}分`.replace(/[^\d分]/g, '')
                        "
                        :parser="value => value.replace('分', '')"
                        v-model="information[1].MultiSelect"
                        @change="changeScore(2)"
                      />
                    </a-col>
                  </a-row>
                </div>
                <!-- 问答题 -->
                <div
                  style="margin-top:10px;margin-bottom:10px"
                  v-if="information[0].Essays != 0"
                >
                  <a-row>
                    <a-col style="margin-left:3px;color:#000;"
                      >问答题
                      <span style="color:#f81d22">
                        x {{ information[0].Essays }}</span
                      ></a-col
                    >
                    <a-col style="margin-top:3px;margin-left:3px" :span="6">
                      <span>每题</span>
                    </a-col>
                    <a-col style="margin-top:3px" :span="10">
                      <a-input-number
                        size="small"
                        :min="0"
                        :max="100"
                        :formatter="
                          value => `${value}分`.replace(/[^\d分]/g, '')
                        "
                        :parser="value => value.replace('分', '')"
                        v-model="information[1].Essays"
                        @change="changeScore(5)"
                      />
                    </a-col>
                  </a-row>
                </div>
              </div>
            </a-col>
            <a-col :span="15">
              <div>
                <a-button @click="showModal">选择题库</a-button>
                <a-button
                  @click="sortByIndex"
                  type="primary"
                  style="margin-left:10px"
                  >按题号排序</a-button
                >
                <a-button
                  @click="sortByType"
                  type="primary"
                  style="margin-left:10px"
                  >按题目类型排序</a-button
                >
              </div>
              <div
                style="margin-top:10px"
                class="demo-infinite-container"
                :infinite-scroll-disabled="busy"
                :infinite-scroll-distance="10"
              >
                <!-- 滑动栏题库 -->
                <a-list :data-source="data">
                  <a-list-item slot="renderItem" slot-scope="item">
                    <a-list-item-meta
                      :description="'答案：' + item.questionAnswer"
                    >
                      <a slot="title">题干：{{ item.questionName }}</a>
                      <a-avatar
                        slot="avatar"
                        size="large"
                        :style="{
                          backgroundColor: '#7265e6',
                          verticalAlign: 'middle'
                        }"
                        >{{ item.index }}
                      </a-avatar>
                    </a-list-item-meta>
                    <div>
                      {{ item.questionType }}
                      <a-input-number
                        size="small"
                        :min="0"
                        :max="100"
                        :precision="0"
                        :formatter="
                          value => `${value}分`.replace(/[^\d分]/g, '')
                        "
                        :parser="value => value.replace('分', '')"
                        v-model="item.score"
                        @change="calcScore"
                      />
                    </div>
                  </a-list-item>
                </a-list>
              </div>
            </a-col>
          </a-row>
        </a-card>

        <a-form-model-item :wrapper-col="{ span: 14, offset: 4 }">
          <a-button type="primary" @click="onSubmit">
            保存
          </a-button>
          <a-button style="margin-left: 10px;" @click="resetForm">
            清空
          </a-button>
          <a-button style="margin-left: 10px;" @click="backCreate">
            返回
          </a-button>
        </a-form-model-item>
      </a-card>
    </a-form-model>

    <!-- 题库选择 -->
    <a-modal
      :visible="visible"
      title="题库选择"
      @ok="handleOk"
      @cancel="handleCancel"
      :maskClosable="false"
      :width="720"
    >
      <a-table :columns="columns" :data-source="questionBankData">
        <a slot="name" slot-scope="text">{{ text }}</a>
        <span slot="tags" slot-scope="tags">
          <template v-for="tag in tags">
            <a-tooltip v-if="tag.length > 10" :key="tag" :title="tag">
              <a-tag :key="tag" color="#f50">
                {{ `${tag.slice(0, 10)}...` }}
              </a-tag>
            </a-tooltip>
            <a-tag
              v-else-if="tag.length != 0"
              :key="tag"
              :color="tag.length > 5 ? '#87d068' : '#108ee9'"
            >
              {{ tag }}
            </a-tag>
          </template>
        </span>
        <template slot="action" slot-scope="text, record">
          <a-popconfirm
            title="确认此题库?"
            ok-text="确定"
            cancel-text="取消"
            @confirm="choiceQuestionBank(record)"
          >
            <a>选择</a>
          </a-popconfirm>
        </template>
      </a-table>
      <a-tag color="red" style="margin-bottom:10px">
        目前只支持直接选择某几个题库的全部试题
      </a-tag>
    </a-modal>
  </div>
</template>

<script>
import infiniteScroll from "vue-infinite-scroll";
const columns = [
  {
    title: "题库名称",
    dataIndex: "name",
    key: "name",
    scopedSlots: { customRender: "name" }
  },
  {
    title: "标签",
    key: "tags",
    dataIndex: "tags",
    scopedSlots: { customRender: "tags" }
  },
  {
    title: "题量",
    dataIndex: "count",
    key: "count",
    width: 80
  },
  {
    title: "操作",
    key: "action",
    scopedSlots: { customRender: "action" }
  }
];

export default {
  directives: { infiniteScroll },
  data() {
    return {
      data: [], // 选择的数据
      questionBankData: [], // 题库信息
      information: [
        { Gap: 0, TorF: 0, Radio: 0, MultiSelect: 0, Essays: 0 }, // 每道题的数量
        { Gap: 0, TorF: 0, Radio: 0, MultiSelect: 0, Essays: 0 }, // 每道题的统一分数
        { total: 0, totalScore: 0 }
      ],
      columns,
      loading: false,
      busy: false,
      labelCol: { span: 4 },
      wrapperCol: { span: 10 },
      other: "",
      form: {
        testName: "",
        testInformation: {}, // 题目统计信息
        testQuestions: [] // 所有的题目和分数
      },
      visible: false,
      rules: {
        testName: [
          {
            required: true,
            message: "试卷名不能为空",
            trigger: "blur"
          }
        ]
      }
    };
  },

  methods: {
    onSubmit() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          // 名字校验通过
          if (this.data.length == 0) this.$message.error("请先添加题目!");
          else {
            // 判断每道题是否都有分数
            for (let i = 0; i < this.data.length; i++) {
              if (this.data[i].score == 0) {
                this.$message.error("请设置相关题目的分数!");
                this.form.testInformation = {};
                this.form.testQuestions = [];
                return false;
              } else {
                this.form.testQuestions.push({
                  qid: this.data[i].id,
                  type: this.data[i].questionType,
                  score: this.data[i].score,
                  name: this.data[i].questionName,
                  answer: this.data[i].questionAnswer
                });
              }
            }
            this.form.testInformation = JSON.stringify(this.information);
            this.form.testQuestions = JSON.stringify(this.form.testQuestions);
            // console.log(JSON.parse(JSON.stringify(this.information)));
            this.$axios
              .post("/create/testes/info", this.form, {
                headers: {
                  Authorization: localStorage.getItem("token")
                }
              })
              .then(res => {
                if (res.data.code == 200) {
                  this.$message.success(res.data.msg);
                  this.backCreate();
                } else {
                  this.$message.error(res.data.msg);
                }
              });
          }
        } else {
          this.$message.error("试卷名不能为空!");
          return false;
        }
      });
    },
    resetForm() {
      this.data = [];
      this.information = [
        { Gap: 0, TorF: 0, Radio: 0, MultiSelect: 0, Essays: 0 },
        { Gap: 0, TorF: 0, Radio: 0, MultiSelect: 0, Essays: 0 },
        { total: 0, totalScore: 0 }
      ];
      this.$refs.ruleForm.resetFields();
    },

    showModal() {
      // console.log(this.information);
      // 点击选择题库之后
      this.visible = true;
      // 发起查看所创建的题库信息
      this.$axios
        .get("/get/questionBank/info", {
          headers: {
            Authorization: localStorage.getItem("token")
          }
        })
        .then(res => {
          if (res.data.code == 200) {
            // console.log(res.data.data);
            for (let i = 0; i < res.data.data.length; i++) {
              res.data.data[i].key = res.data.data[i].id;
              // 处理标签
              res.data.data[i].tags = res.data.data[i].tags.split(",");
              res.data.data[i].score = 0;
              // 处理时间
              res.data.data[i].createdTime = res.data.data[
                i
              ].createdTime.replace("T", " ");
            }
            this.questionBankData = res.data.data;
          } else {
            this.$message.error(res.data.msg);
          }
        });
    },
    handleOk(e) {
      this.visible = false;
    },
    handleCancel(e) {
      this.visible = false;
    },
    // 快捷更改所有分数后 需要更改data里的值
    changeScore(type) {
      this.information[2].totalScore = 0;
      for (let i = 0; i < this.data.length; i++) {
        if (this.data[i].type == type) {
          if (type == 1) this.data[i].score = this.information[1].Radio;
          else if (type == 2)
            this.data[i].score = this.information[1].MultiSelect;
          else if (type == 3) this.data[i].score = this.information[1].TorF;
          else if (type == 4) this.data[i].score = this.information[1].Gap;
          else this.data[i].score = this.information[1].Essays;
        }
        this.information[2].totalScore += parseInt(this.data[i].score);
      }
    },
    calcScore() {
      this.information[2].totalScore = 0;
      for (let i = 0; i < this.data.length; i++) {
        this.information[2].totalScore += parseInt(this.data[i].score);
      }
    },
    choiceQuestionBank(record) {
      // console.log(record);
      this.$axios
        .get("/get/questions/type/" + record.id, {
          headers: {
            Authorization: localStorage.getItem("token")
          }
        })
        .then(res => {
          if (res.data.code == 200) {
            // 获取长度
            let len = this.data.length;

            for (let idx = len, i = 0; i < res.data.data.length; i++, idx++) {
              res.data.data[i].index = idx + 1;
              res.data.data[i].key = res.data.data[i].id;
              // 处理类型
              if (res.data.data[i].type == 1) {
                res.data.data[i].questionType = "单选题";
                this.information[0].Radio++;
              } else if (res.data.data[i].type == 2) {
                res.data.data[i].questionType = "多选题";
                this.information[0].MultiSelect++;
              } else if (res.data.data[i].type == 3) {
                res.data.data[i].questionType = "判断题";
                res.data.data[i].questionAnswer =
                  res.data.data[i].questionAnswer == "1" ? "正确" : "错误";
                this.information[0].TorF++;
              } else if (res.data.data[i].type == 4) {
                res.data.data[i].questionType = "填空题";
                this.information[0].Gap++;
              } else if (res.data.data[i].type == 5) {
                res.data.data[i].questionType = "问答题";
                this.information[0].Essays++;
              }
              res.data.data[i].score = 0;
              // 处理标签
              res.data.data[i].tags = res.data.data[i].questionTags.split(",");
              // 处理时间
              res.data.data[i].createdTime = res.data.data[
                i
              ].createdTime.replace("T", " ");
            }
            if (len == 0) {
              this.data = res.data.data;
            } else {
              for (var i = 0; i < res.data.data.length; i++) {
                for (var j = 0; j < this.data.length; j++) {
                  // 循环已有的数据
                  if (this.data[j].id == res.data.data[i].id) {
                    this.$message.error("不能重复添加题目");
                    i = res.data.data.length;
                    break;
                  }
                }
                if (i == res.data.data.length) break;
                this.data.push(res.data.data[i]);
              }
            }

            console.log("data");
            console.log(this.data);
            this.information[2].total = this.data.length;
          } else {
            this.$message.error(res.data.msg);
          }
        });
    },
    sortByIndex() {
      if (this.data.length == 0) {
        this.$message.error("请先添加题目!");
      } else {
        this.data.sort(function(a, b) {
          return a.index - b.index;
        });
      }
    },
    sortByType() {
      if (this.data.length == 0) {
        this.$message.error("请先添加题目!");
      } else {
        this.data.sort(function(a, b) {
          return a.type - b.type;
        });
      }
    },
    backCreate() {
      this.$router.push({ path: "/home/exam/examinationPaperManagement" });
    }
  }
};
</script>

<style scoped>
.demo-infinite-container {
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  overflow: auto;
  padding: 8px 24px;
  height: 500px;
}
.demo-loading-container {
  position: absolute;
  bottom: 40px;
  width: 100%;
  text-align: center;
}
.ant-modal-content {
  border-radius: 0px;
}
</style>
